import {createAsyncThunk} from "@reduxjs/toolkit";
import {requestDelete, requestGet, requestPost, requestPut} from "util/request";
import {ConsumePage, PagingData} from "type/Page";
import {Consume} from "type/Consume";
import {ConsumeItem} from "type/ConsumeItem";
import {Result} from "type/Result";

/**
 * 异步获取消费记录选项数据,如果成功返回消费项目数据,否则返回null
 */
export const fetchLoadItemOptions = createAsyncThunk(
    "consume/fetchLoadItemOptions",
    async () => {
        const res = await requestGet<ConsumeItem[]>("/record/consume-item/list").then(res=>res) ;
        if (res.success){
            return res.data ;
        }
        return null ;
    }
) ;

/**
 * 异步获取消费记录分页数据,如果成功返回分页数据,否则返回null
 */
export const fetchConsumePageData = createAsyncThunk(
    "consume/fetchConsumePageData",
    async (paging: PagingData) => {
       const result = await requestGet<ConsumePage>(`/record/consume/page/${paging.current}/${paging.pageSize}/${paging.month}`).then(res => res) ;
       if (result.success){
           return result.data ;
       }
       return null ;
    }
);
/**
 * 异步添加消费记录
 * @return Result<number>
 */
export const fetchAddConsume = createAsyncThunk(
    "consume/fetchAddConsume",
    async (consume: Consume) => {
        return await requestPut<number>("/record/consume",consume).then(res => res) ;
    }
) ;

/**
 * 异步修改消费记录反回结果
 */
interface UpdateConsume {
    /**
     * 服务返回结果,如果成功返回1,否则返回0
     */
    result: Result<number> ;
    /**
     * 修改后的消费记录
     */
    consume: Consume ;
}
/**
 * 异步修改消费记录
 * @return Result<number>
 */
export const fetchUpdateConsume = createAsyncThunk(
    "consume/fetchUpdateConsume",
    async (consume: Consume): Promise<UpdateConsume> => {
        const res = await requestPost<number>("/record/consume",consume).then(res => res) ;
            return {
                result: res,
                consume: consume
            };
    }
) ;

interface DeleteConsume {
    /**
     * 服务器执行删除的结果
     */
    result: boolean ;
    /**
     * 删除的消费记录ID
     */
    id: number ;

}

/**
 * 异步删除消费记录,返回删除结果和删除的消费记录ID
 */
export const fetchDeleteConsume = createAsyncThunk(
    "consume/fetchDeleteConsume",
    async (id: number): Promise<DeleteConsume> => {
        const res = await requestDelete<number>("/record/consume/" + id).then(res => res) ;
        return {
            result: res.success,
            id: id
        } ;
    }
) ;